package com.enlf.utils.lock;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.BooleanUtil;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * _*_ coding : utf-8 _*_
 *
 * @Time : 2023/9/30 16:40
 * @Author : 计201任思伟
 * @File : SimpleRedisLock
 * @Project : enjoy-life
 */
public class SimpleRedisLock implements Ilock{
    //redis模板
    private StringRedisTemplate stringRedisTemplate;
    //锁名称
    private String name;

    public SimpleRedisLock(StringRedisTemplate stringRedisTemplate, String name) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.name = name;
    }

    public static final String KEY_PREFIX = "lock:";
    public static final String ID_PREFIX = UUID.randomUUID().toString(true)+"-";
    //先加载lua脚本
    public static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        //设置加载文件的路径
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        //设置返回值类型
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    /**
     *
     * 尝试获取互斥锁
     * @param timeOutSec 持有锁的过期时间，过期自动释放
     * @return 是否获取锁
     */
    @Override
    public boolean tryLock(long timeOutSec) {
        //多个线程访问一个redis，起到一个分布式锁的效果,在value里对线程加锁
        //1.获取当前线程值
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        //2.使用SETNX设置互斥锁和过期时间
        Boolean success = stringRedisTemplate.opsForValue()
                .setIfAbsent(KEY_PREFIX + name, threadId, timeOutSec, TimeUnit.SECONDS);
        //Boolean是包装类需要拆箱，如果success为null，拆箱过程容易空指针
        return Boolean.TRUE.equals(success);
    }


    /**
     * 释放锁
     */
    @Override
    public void unLock() {
        //基于lua脚本实现原子性,redis没有实现事务，所以原生无法保证原子性
        //调用lua脚本
        stringRedisTemplate.execute(
                UNLOCK_SCRIPT,
                Collections.singletonList(KEY_PREFIX + name),//将单个对象转化成list
                ID_PREFIX + Thread.currentThread().getId());
    }
    /*@Override
    public void unLock() {
        //判断当前锁的key是否与当前线程一致
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        String id = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
        //判断是否一致，一致则释放
        if (threadId.equals(id)){
            //删除当前键
            stringRedisTemplate.delete(KEY_PREFIX + name);
        }
    }*/
}
